package com.yly.doctorapp.startpager

import android.Manifest
import android.annotation.SuppressLint
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Build
import android.os.Bundle
import android.os.Handler
import android.os.Message
import android.support.v4.app.ActivityCompat
import com.apkfuns.logutils.LogUtils
import com.igexin.sdk.PushManager
import com.yly.doctorapp.base.BaseActivity
import com.yly.doctorapp.constant.Configution
import com.yly.doctorapp.push.DoctorIntentService
import com.yly.doctorapp.push.DoctorPushService
import com.yly.doctorapp.ui.home.HomePagerActivity
import com.yly.doctorapp.ui.usercenter.LoginActivity
import com.zhcx.zhcxlibrary.utils.SPUtils
import com.zhcx.zhcxlibrary.utils.StringUtils
import kotlinx.android.synthetic.main.activity_startpager.*
import java.io.File
import java.io.File.separator


/**
 * ProjectName: Interrogation
 * PackageName: com.yly.interrogation.ui.personalcenter
 * description:启动页
 * Date：2018/8/14 9:42
 * Author：Steven J
 * ClassName:SplashActivity
 * Modify The Note:
 **/
class SplashActivity : BaseActivity() {
    private var mSputils: SPUtils? = null
    public var REQUEST_PERMISSION: Int = 0
    // DemoPushService.class 自定义服务名称, 核心服务
    private val userPushService = DoctorPushService::class.java
    private val mHandler = @SuppressLint("HandlerLeak")
    object : Handler() {
        override fun handleMessage(msg: Message?) {
            super.handleMessage(msg)
            when (msg!!.what) {
                START_COUNTING -> {
                    val count: Int = msg.obj as Int
                    textDaoshu.text = "${count}s 关闭"
                    if (count > 0) {
                        val msg1 = obtainMessage()
                        msg1.what = START_COUNTING
                        msg1.obj = count - 1
                        sendMessageDelayed(msg1, 1000)
                    } else {
                        lodIn()
                    }
                }
            }
        }
    }

    companion object {
        private const val START_COUNTING = 1
        private const val COUNT_NUMBER = 5
    }


    override fun getNaviteColor(): Int {
        return 1
    }

    override fun getContentLayoutId(): Int {
        return com.yly.doctorapp.R.layout.activity_startpager
    }

    override fun initView(savedInstanceState: Bundle?) {
        mSputils = SPUtils(applicationContext)
        if (!isTaskRoot) {
            finish()
            return
        }
        if (intent != null) {
            if (intent.flags and Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT != 0) {
                finish()
                return
            }
        }
        val msg = mHandler.obtainMessage()
        msg.what = START_COUNTING
        msg.obj = COUNT_NUMBER
        mHandler.sendMessageDelayed(msg, 10)
        textDaoshu.setOnClickListener {
            mHandler.removeCallbacksAndMessages(null)
            lodIn()
        }

        val pkgManager = packageManager

        // 读写 sd card 权限非常重要, android6.0默认禁止的, 建议初始化之前就弹窗让用户赋予该权限
        val sdCardWritePermission = pkgManager.checkPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE, packageName) == PackageManager.PERMISSION_GRANTED

        // read phone state用于获取 imei 设备信息
        val phoneSatePermission = pkgManager.checkPermission(Manifest.permission.READ_PHONE_STATE, packageName) == PackageManager.PERMISSION_GRANTED

        if (Build.VERSION.SDK_INT >= 23 && !sdCardWritePermission || !phoneSatePermission) {
            requestPermission()
        } else {
            PushManager.getInstance().initialize(this.applicationContext, userPushService)
        }

        // 注册 intentService 后 PushDemoReceiver 无效, sdk 会使用 DemoIntentService 传递数据,
        // AndroidManifest 对应保留一个即可(如果注册 DemoIntentService, 可以去掉 PushDemoReceiver, 如果注册了
        // IntentService, 必须在 AndroidManifest 中声明)
        PushManager.getInstance().registerPushIntentService(this.applicationContext, DoctorIntentService::class.java)
        // cpu 架构
        LogUtils.d("cpu arch = " + if (Build.VERSION.SDK_INT < 21) Build.CPU_ABI else Build.SUPPORTED_ABIS[0])

        // 检查 so 是否存在
        val file = File(this.applicationInfo.nativeLibraryDir + separator + "libgetuiext2.so")
        LogUtils.e("libgetuiext2.so exist = " + file.exists())
    }

    override fun initData() {
    }


    private fun lodIn() {
        if (!StringUtils.isEmpty(mSputils!!.getString(Configution.USERPHONE)) && !StringUtils.isEmpty(mSputils!!.getString(Configution.USERPASSWORD))) {
            val mIntent = Intent(this@SplashActivity, HomePagerActivity::class.java)
            mIntent.putExtra("type", "0")
            startActivity(mIntent)
            finish()
        } else {
            val mIntent = Intent(this@SplashActivity, LoginActivity::class.java)
            startActivity(mIntent)
            finish()
        }
    }

    private fun requestPermission() {
        ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_PHONE_STATE), REQUEST_PERMISSION)
    }

    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) {
        if (requestCode == REQUEST_PERMISSION) {
            if (grantResults.size == 2 && grantResults[0] == PackageManager.PERMISSION_GRANTED
                    && grantResults[1] == PackageManager.PERMISSION_GRANTED) {
                PushManager.getInstance().initialize(this.applicationContext, userPushService)
            } else {
                LogUtils.e("We highly recommend that you need to grant the special permissions before initializing the SDK, otherwise some " + "functions will not work")
                PushManager.getInstance().initialize(this.applicationContext, userPushService)
            }
        } else {
            super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        }
    }


    override fun onDestroy() {
        super.onDestroy()
    }
}